import { isFn } from './verify'

export const beforeDispose = (from, count, self, params) => {
	const id = from[count]++
	
	from[self].push({ id, ...params })

	return () => {
		const index = from[self].findIndex(item => item.id === id)

		if (index > -1) return from[self].splice(index, 1)
	}
}

// export const addListener = (from, reg, pipe) => {
// 	const id = from.listenerId++

// 	from.listeners.push({ id, reg, pipe })

// 	return () => {
// 		const index = from.listeners.findIndex(item => item.id === id)
		
// 		if (index > -1) return from.listeners.splice(index, 1)
// 	}
// }

export const getListenerData = (from, params, { currentPath, pathname, currentQuery }) => {

	return from.listeners.reduce((a, b) => {
		if (new RegExp(`^${b.reg}/`).test(`${currentPath}/`)) {
			if (isFn(b.pipe)) {
				const getParams = b.pipe(a, { fullPath: pathname, path: currentPath, query: { ...currentQuery } }) || {}

				return Object.assign(getParams, a)
			}

			return a
		}

		return a
	}, params)
}